package com.dmc.conf;

import io.swagger.annotations.ApiOperation;
import lombok.Data;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.ParameterBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.schema.ModelRef;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Parameter;
import springfox.documentation.service.ResponseMessage;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

import java.util.ArrayList;
import java.util.List;

@Configuration
@EnableSwagger2
@Data
@ComponentScan("com.dmc.controller")
public class SwaggerConfig {

    @Value("${spring.profiles.active}")
    private String active;

    @Bean
    public Docket createRestApi() {
        active = StringUtils.isBlank(active)?"dev":active;
        Docket docket = null;
        String serviceUrl = null;
        if(active.indexOf("test") > -1){
            serviceUrl = "www.baitongsc.com";
        }else if(active.indexOf("dev") > -1){
            serviceUrl = "localhost:80";
        }
        List<Parameter> parameters = new ArrayList<>();
        parameters.add(new ParameterBuilder()
                .name("Authorization")
                .description("认证token")
                .modelRef(new ModelRef("string"))
                .parameterType("header")
                .required(false)
                .build());
        boolean isPdt = active.indexOf("prod") > -1;
        docket = new Docket(DocumentationType.SWAGGER_2).enable(!isPdt).apiInfo(apiInfo())
                .globalOperationParameters(parameters).select()
                .apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))
                .paths(PathSelectors.any())
                .build().pathMapping("/").host(serviceUrl);
        return docket;
    }

    private List<ResponseMessage> responseMessageList(){
        List<ResponseMessage> list = new ArrayList<>();
        return list;
    }

    private ApiInfo apiInfo() {
        String serviceUrl = "localhost:8081";
        return new ApiInfoBuilder()
                .title("分销电商")
                .description("分销电商文档")
                .termsOfServiceUrl(serviceUrl)
                .version("1.0")
                .build();
    }
}
